package com.example.framework.mqtt.emqx.config;

import com.example.framework.mqtt.core.client.impl.DefaultClientConnectListener;
import com.example.framework.mqtt.core.config.MessageListenerInitialization;
import com.example.framework.mqtt.core.config.MessageListenerProcessor;
import com.example.framework.mqtt.core.utils.MqttClientUtil;
import com.example.framework.mqtt.emqx.EmqxPlatformClient;
import com.example.framework.mqtt.emqx.properties.EmqxProperties;
import net.dreamlu.iot.mqtt.core.client.IMqttClientConnectListener;
import net.dreamlu.iot.mqtt.core.client.MqttClient;
import net.dreamlu.iot.mqtt.core.client.MqttClientCreator;
import org.springframework.boot.autoconfigure.condition.ConditionalOnBean;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Import;

/**
 * <p>
 *  Emqx Platform Client Initialization
 * </p>
 *
 * @author sfjiang
 * @since 2024/11/26 17:43
 */
@Import(MessageListenerInitialization.class)
@Configuration
@ConditionalOnProperty(
        prefix = EmqxProperties.PREFIX,
        name = "enabled",
        havingValue = "true")
@EnableConfigurationProperties(EmqxProperties.class)
public class EmqxPlatformClientInitialization {

    @Bean
    @ConditionalOnMissingBean(IMqttClientConnectListener.class)
    public IMqttClientConnectListener clientConnectListener() {
        return new DefaultClientConnectListener();
    }

    @Bean
    @ConditionalOnBean(IMqttClientConnectListener.class)
    public EmqxPlatformClient emqxPlatformClient(EmqxProperties properties,
                                                 IMqttClientConnectListener clientConnectListener) {
        MqttClientCreator clientCreator = MqttClientUtil.initMqttClient(properties.getConfig(), clientConnectListener);
        MqttClient mqttClient= clientCreator.connectSync();
        return new EmqxPlatformClient(mqttClient);
    }
}
